'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  // context.env, context.version, context.memoryLimitInMB
  // event.queryStringParameters
  
  // 获取客户端上传的参数
  const { page = 1, pageSize = 10, searchQuery = '' } = event;
  
  // 获取当前登录用户的uid
  const { uid } = context.auth;
  
  if (!uid) {
    return {
      errCode: 'NOT_LOGIN',
      errMsg: '用户未登录'
    }
  }
  
  const collection = db.collection('auctions');
  
  // 构建查询条件
  let whereCondition = {
    invited_supplier_ids: uid,
    status: 'bidding'
  };
  
  // 如果有搜索查询
  if (searchQuery) {
    whereCondition = {
      ...whereCondition,
      [dbCmd.or]: [
        { title: new RegExp(searchQuery, 'i') },
        { serial_number: new RegExp(searchQuery, 'i') }
      ]
    }
  }
  
  // 查询数据库
  const res = await collection.where(whereCondition)
    .skip((page - 1) * pageSize)
    .limit(pageSize)
    .orderBy('create_time', 'desc')
    .get();
    
  const { total } = await collection.where(whereCondition).count();
  
  // 返回结果
  return {
    errCode: 0,
    errMsg: '查询成功',
    data: res.data,
    total,
    hasMore: total > page * pageSize
  }
};